package org.linlinjava.litemall.admin.service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.db.domain.WxMsgReplyRule;
import org.linlinjava.litemall.db.service.WxMsgReplyRuleService;
import org.linlinjava.litemall.db.util.TaskExcutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;

@Service
public class WxMsgReplyService {
	private final Log logger = LogFactory.getLog(WxMsgReplyService.class);
	@Autowired
	private WxMpService wxMpService;
	@Autowired
	private WxMsgReplyRuleService wxMsgReplyRuleService;

	/**
	 * 根据规则配置通过微信客服消息接口自动回复消息
	 *
	 *
	 * @param appid      公众号appid
	 * @param exactMatch 是否精确匹配
	 * @param toUser     用户openid
	 * @param keywords   匹配关键词
	 * @return 是否已自动回复，无匹配规则则不自动回复
	 */
	public boolean tryAutoReply(String toUser, String keywords) {
		try {
			List<WxMsgReplyRule> replyList = wxMsgReplyRuleService.selectAll(keywords);
			if (replyList.isEmpty()) {
				return false;
			}
			long delay = 0;
			for (WxMsgReplyRule rule : replyList) {
				TaskExcutor.schedule(() -> {
					this.MsgReplyrule(toUser, rule.getReplyType(), rule.getReplyContent());
				}, delay, TimeUnit.MILLISECONDS);
			}
			return true;
		} catch (Exception e) {
			logger.error("自动回复出错：", e);
		}
		return false;
	}

	public void MsgReplyrule(String toUser, String replyType, String replyContent) {
		try {
			if (WxConsts.KefuMsgType.TEXT.equals(replyType)) {
				this.replyText(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.IMAGE.equals(replyType)) {
				this.replyImage(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.VOICE.equals(replyType)) {
				this.replyVoice(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.VIDEO.equals(replyType)) {
				this.replyVideo(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.MUSIC.equals(replyType)) {
				this.replyMusic(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.NEWS.equals(replyType)) {
				this.replyNews(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.MPNEWS.equals(replyType)) {
				this.replyMpNews(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.WXCARD.equals(replyType)) {
				this.replyWxCard(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.MINIPROGRAMPAGE.equals(replyType)) {
				this.replyMiniProgram(toUser, replyContent);
			} else if (WxConsts.KefuMsgType.MSGMENU.equals(replyType)) {
				this.replyMsgMenu(toUser, replyContent);
			}
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void replyText(String toUser, String content) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.TEXT().toUser(toUser).content(content).build());

		//JSONObject json = new JSONObject().fluentPut("content", content);
		//// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.TEXT,toUser,json));
	}

	public void replyImage(String toUser, String mediaId) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.IMAGE().toUser(toUser).mediaId(mediaId).build());

		//JSONObject json = new JSONObject().fluentPut("mediaId", mediaId);
		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.IMAGE,toUser,json));
	}

	public void replyVoice(String toUser, String mediaId) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.VOICE().toUser(toUser).mediaId(mediaId).build());

		//JSONObject json = new JSONObject().fluentPut("mediaId", mediaId);
		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.VOICE,toUser,json));
	}

	public void replyVideo(String toUser, String mediaId) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.VIDEO().toUser(toUser).mediaId(mediaId).build());

		//JSONObject json = new JSONObject().fluentPut("mediaId", mediaId);
		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.VIDEO,toUser,json));
	}

	public void replyMusic(String toUser, String musicInfoJson) throws WxErrorException {
		JSONObject json = JSON.parseObject(musicInfoJson);
		wxMpService.getKefuService()
				.sendKefuMessage(WxMpKefuMessage.MUSIC().toUser(toUser).musicUrl(json.getString("musicurl"))
						.hqMusicUrl(json.getString("hqmusicurl")).title(json.getString("title"))
						.description(json.getString("description")).thumbMediaId(json.getString("thumb_media_id"))
						.build());

		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.IMAGE,toUser,json));
	}

	/**
	 * 发送图文消息（点击跳转到外链） 图文消息条数限制在1条以内
	 * 
	 * @param toUser
	 * @param newsInfoJson
	 * @throws WxErrorException
	 */
	public void replyNews(String toUser, String newsInfoJson) throws WxErrorException {
		WxMpKefuMessage.WxArticle wxArticle = JSON.parseObject(newsInfoJson, WxMpKefuMessage.WxArticle.class);
		List<WxMpKefuMessage.WxArticle> newsList = new ArrayList<WxMpKefuMessage.WxArticle>() {
			{
				add(wxArticle);
			}
		};
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.NEWS().toUser(toUser).articles(newsList).build());

		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.NEWS,toUser,JSON.parseObject(newsInfoJson)));
	}

	/**
	 * 发送图文消息（点击跳转到图文消息页面） 图文消息条数限制在1条以内
	 * 
	 * @param toUser
	 * @param mediaId
	 * @throws WxErrorException
	 */
	public void replyMpNews(String toUser, String mediaId) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.MPNEWS().toUser(toUser).mediaId(mediaId).build());

		//JSONObject json = new JSONObject().fluentPut("mediaId", mediaId);
		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.MPNEWS,toUser,json));
	}

	public void replyWxCard(String toUser, String cardId) throws WxErrorException {
		wxMpService.getKefuService().sendKefuMessage(WxMpKefuMessage.WXCARD().toUser(toUser).cardId(cardId).build());

		//JSONObject json = new JSONObject().fluentPut("cardId", cardId);
		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.WXCARD,toUser,json));
	}

	public void replyMiniProgram(String toUser, String miniProgramInfoJson) throws WxErrorException {
		JSONObject json = JSON.parseObject(miniProgramInfoJson);
		wxMpService.getKefuService()
				.sendKefuMessage(WxMpKefuMessage.MINIPROGRAMPAGE().toUser(toUser).title(json.getString("title"))
						.appId(json.getString("appid")).pagePath(json.getString("pagepath"))
						.thumbMediaId(json.getString("thumb_media_id")).build());

		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.IMAGE,toUser,json));
	}

	public void replyMsgMenu(String toUser, String msgMenusJson) throws WxErrorException {
		JSONObject json = JSON.parseObject(msgMenusJson);
		List<WxMpKefuMessage.MsgMenu> msgMenus = json.getJSONArray("list").toJavaList(WxMpKefuMessage.MsgMenu.class);
		wxMpService.getKefuService()
				.sendKefuMessage(WxMpKefuMessage.MSGMENU().toUser(toUser).headContent(json.getString("head_content"))
						.tailContent(json.getString("tail_content")).msgMenus(msgMenus).build());

		// wxMsgService.addWxMsg(WxMsg.buildOutMsg(WxConsts.KefuMsgType.IMAGE,toUser,json));
	}
}
